package com.junko.admin.controller.back;

import com.junko.admin.controller.BaseBackendController;
import com.junko.core.constant.ConstantWebContext;
import com.junko.core.tool.ToolPassword;
import com.junko.core.tool.ToolWeb;
import com.junko.model.JsonResult;
import com.junko.model.back.Admin;
import com.junko.service.back.IAdminService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/b/login")
public class LoginController extends BaseBackendController {
    private Logger logger = LogManager.getLogger(LoginController.class);
    @Resource
    private IAdminService adminService;

    @RequestMapping
    public String index(){
        return "/back/login/index";
    }

    /**
     * 登录
     */
    @RequestMapping("doLogin")
    public @ResponseBody
    JsonResult login(HttpServletResponse response) {
        String account = getPara("account");
        String password = getPara("password");
        Boolean autoLogin = getParaToBool("autoLogin", false);
        Admin admin = adminService.findByAccount(account);
        if (admin == null) {
            return fail("账号不存在");
        }
        if (!ToolPassword.checkPassword(admin.getSalt(), admin.getPassword(), password)) {
            return fail("账号或密码不正确");
        }
        setCurrentAdmin(response, admin, autoLogin);
        return success();
    }

    /**
     * 注销登录
     */
    @RequestMapping("logout")
    public String logout(HttpServletResponse response) {
        ToolWeb.addCookie(request, response, "", "/", true, ConstantWebContext.cookie_authmark, null, 0);
        return "redirect:/b";
    }
}